package com.ck.serviceImpl;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.providers.encoding.Md5PasswordEncoder;

import com.ck.dao.AdminDAO;
import com.ck.dao.StudentDAO;
import com.ck.dao.TeacherDAO;
import com.ck.domain.Admin;
import com.ck.domain.Student;
import com.ck.domain.Teacher;
import com.ck.service.BasicService;

public class BasicServiceImpl implements BasicService {
	
	private AdminDAO adminDAO;
	private TeacherDAO teacherDAO;
	private StudentDAO studentDAO;

	public void setAdminDAO(AdminDAO adminDAO) {
		this.adminDAO = adminDAO;
	}

	public void setTeacherDAO(TeacherDAO teacherDAO) {
		this.teacherDAO = teacherDAO;
	}

	public void setStudentDAO(StudentDAO studentDAO) {
		this.studentDAO = studentDAO;
	}

	public boolean login(String username, String password, Integer type,
			Map model, HttpServletRequest request) {

		HttpSession session = request.getSession();
		
		switch (type) {
		case 1:
			Student student = studentDAO.getStudentByUsername(username);
			if (student != null && md5(password).equals(student.getPassword())) {
				session.setAttribute("studentID", student.getId());
				session.setAttribute("studentUsername", student.getUsername());
				session.setAttribute("studentTruename", student.getTruename());
				//更新最近登录时间
				student.setLast_login_time(new Date());
				studentDAO.updateStudentLastLoginTime(student);
				return true;
			} else {
				model.put("error_user", "用户名或密码错误！");
				return false;
			}
		case 2:
			Teacher teacher = teacherDAO.getTeacherByUsername(username);
			if (teacher != null && md5(password).equals(teacher.getPassword())) {
				session.setAttribute("teacherID", teacher.getId());
				session.setAttribute("teacherUsername", teacher.getUsername());
				session.setAttribute("teacherTruename", teacher.getTruename());
				//更新最近登录时间
				teacher.setLast_login_time(new Date());
				teacherDAO.updateTeacherLastLoginTime(teacher);
				return true;
			} else {
				model.put("error_user", "用户名或密码错误！");
				return false;
			}
		case 3:
			Admin admin = adminDAO.getAdminByUsername(username);
			if (admin != null && md5(password).equals(admin.getPassword())) {
				session.setAttribute("adminID", admin.getId());
				session.setAttribute("adminUsername", admin.getUsername());
				session.setAttribute("superadmin", admin.getSuperadmin());
				//更新最近登录时间
				admin.setLast_login_time(new Date());
				adminDAO.updateAdminLastLoginTime(admin);
				return true;
			} else {
				model.put("error_user", "用户名或密码错误！");
				return false;
			}
		default:
			model.put("error_user", "请选择登录类型！");
			return false;
		}
	}
	
	private String md5(String password) {
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		return md5.encodePassword(password, new String("canyouguessme"));
	}

}
